package com.faryangsh.scheduleTask.scheduling;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * 定时任务执行器自动配置类
 *
 */
@Configuration
@EnableConfigurationProperties(SchedulingProperties.class)
@ConditionalOnClass(SchedulingConfigurer.class)
@ConditionalOnProperty(prefix = "scheduling.conf.prefix", name = "enabled", havingValue = "true")
@EnableScheduling
public class SchedulingAutoConfiguration implements SchedulingConfigurer {

    private final SchedulingProperties schedulingProperties;

    public SchedulingAutoConfiguration(SchedulingProperties schedulingProperties) {
        this.schedulingProperties = schedulingProperties;
    }

    /**
     * 通过@Scheduled注解创建的定时任务，默认共享同一个执行线程，当存在多个定时任务时需要串行执行、效率低
     * - 可根据服务实际配置的定时任务数，适当放大共享的线程池，以提高定时任务执行性能
     *
     * @param scheduledTaskRegistrar 定时任务配置器
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(schedulingProperties.getPoolSize());
        taskScheduler.setThreadNamePrefix(schedulingProperties.getSchedulingThreadPrefix());
        taskScheduler.initialize();
        scheduledTaskRegistrar.setTaskScheduler(taskScheduler);
    }
}
